package com.ruitaowang.admin.websocket;

import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.SysUser;
import com.ruitaowang.core.domain.UserOnline;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.UserOnlineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.socket.messaging.SessionConnectEvent;

import java.security.Principal;


public class WebSocketConnectHandler<S>
		implements ApplicationListener<SessionConnectEvent> {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketConnectHandler.class);
	private SimpMessageSendingOperations messagingTemplate;
	private UserOnlineService userOnlineService;
	private SysUserService userService;
	/**
	 * 初始化的时候，执行
	 *
	 */
	public WebSocketConnectHandler(SimpMessagingTemplate messagingTemplate,
								   UserOnlineService userOnlineService,
								   SysUserService userService){
		super();
		this.messagingTemplate = messagingTemplate;
		this.userOnlineService = userOnlineService;
		this.userService = userService;
	}
	/**
	 * 第一次建立链接的时候，执行
	 */
	public void onApplicationEvent(SessionConnectEvent event) {
		MessageHeaders headers = event.getMessage().getHeaders();
		LOGGER.info("headers", headers);
		LOGGER.info("headers", "--------------------------------------------------");
		Principal user = SimpMessageHeaderAccessor.getUser(headers);
		LOGGER.debug("user {}, 进入了房间", user);
		if(user==null){
			return;
		}
		LOGGER.debug("user.name {}", user.getName());
		String[] token = user.getName().split("-");
		if (token.length==2){
			Long userId = Long.valueOf(token[0]);
			SysUser sysUser = userService.selectByPK(userId);
			UserOnline entity = new UserOnline();
			entity.setUserId(sysUser.getId());
			entity.setNickname(sysUser.getNickname());
			entity.setHeadimgurl(sysUser.getHeadimgurl());
			entity.setRoomId(Long.valueOf(token[1]));
			entity.setRemark(SimpMessageHeaderAccessor.getSessionId(headers));
			try {
				userOnlineService.insert(entity);
				LOGGER.debug("try user.name {}", user.getName());
				this.messagingTemplate.convertAndSend("/topic/online/"+entity.getRoomId(), MsgOut.success(1));
			}catch (Exception e){
				userOnlineService.updateByUserIdAndRoomId(Long.valueOf(user.getName().split("-")[0]), Long.valueOf(user.getName().split("-")[1]), (byte) 0);
			}
			//notify to online
		}
	}

}
